package com.base.cn.platform.os.common.tools;

import com.base.cn.platform.os.common.utils.StringUtils;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * spring 接受date类型转换工具类
 */
public class DateEditor extends PropertyEditorSupport {
    private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
    private static final DateFormat TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private DateFormat dateFormat;
    private boolean allowEmpty = true;

    public DateEditor(){}

    public DateEditor(DateFormat dateFormat){
        this.dateFormat = dateFormat;
    }

    public DateEditor(DateFormat dateFormat,boolean allowEmpty){
        this.dateFormat = dateFormat;
        this.allowEmpty = allowEmpty;
    }

    @Override
    public String getAsText() {
        Date value = (Date) this.getValue();
        DateFormat dateFormat = this.dateFormat;
        if(dateFormat==null){
            dateFormat = TIME_FORMAT;
        }
        return (value !=null ? dateFormat.format(value) : "");
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if(this.allowEmpty && !StringUtils.hasText(text)){
            this.setValue(null);
        }else{
            try{
                if(this.dateFormat != null){
                    this.setValue(this.dateFormat.parse(text));
                }else{
                    if(text.contains(":")){
                        this.setValue(TIME_FORMAT.parse(text));
                    }else{
                        this.setValue(DATE_FORMAT.parse(text));
                    }
                }
            }catch (ParseException ex){
                throw new IllegalArgumentException("Could not parse date:"+ex.getMessage() , ex);
            }
        }
    }
}
